package com.czk.bootlettuce.redlock.demo;

import org.redisson.Redisson;
import org.redisson.RedissonRedLock;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 在进行加锁操作时，RedLock会向每个Redis节点发送相同的命令请求，每个节点都会去竞争锁，如果至少在大多数节点上成功获取了锁，那么就认为加锁成功。
 * 反之，如果大多数节点上没有成功获取锁，则加锁失败。这样就可以避免因为某个Redis节点故障导致加锁失败的情况发生
 *
 * @author chenzhangkun
 * @ClassName RedLockDemo
 * @description: TODO
 * @date 2024年11月15日
 */
@RestController
public class RedLockDemo {


	@Autowired
	@Qualifier("firstRedLockServer")
	private Config firstRedLockServer;
	@Autowired
	@Qualifier("secondRedLockServer")
	private Config secondRedLockServer;
	@Autowired
	@Qualifier("thirdRedLockServer")
	private Config thirdRedLockServer;

	@GetMapping("/redis/red/lock")
	public void tryRedLock() {
		RedissonClient firstRedLockServerClient = Redisson.create(firstRedLockServer);
		RLock lock1 = firstRedLockServerClient.getLock("czk:readlock");
		RedissonClient secondRedLockServerClient = Redisson.create(secondRedLockServer);
		RLock lock2 = secondRedLockServerClient.getLock("czk:readlock");
		RedissonClient thirdRedLockServerClient = Redisson.create(thirdRedLockServer);
		RLock lock3 = thirdRedLockServerClient.getLock("czk:readlock");
		RedissonRedLock redissonRedLock = new RedissonRedLock(lock1, lock2, lock3);
		boolean b = redissonRedLock.tryLock();
		System.out.println(b ? "成功" : "失败");
	}

}
